package com.rfsp.mcp.controller.bank;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.github.pagehelper.PageInfo;
import com.rfsp.common.base.ResultListVO;
import com.rfsp.common.base.ResultVO;
import com.rfsp.common.interceptor.Token;
import com.rfsp.common.interceptor.TokenType;
import com.rfsp.common.log.TrcMsg;
import com.rfsp.common.pojo.sdto.PageSDTO;
import com.rfsp.common.pojo.vo.DictVO;
import com.rfsp.common.service.OrgService;
import com.rfsp.common.service.ParamService;
import com.rfsp.common.shiro.ShiroUtils;
import com.rfsp.common.util.*;
import com.rfsp.mcp.enums.MiPayDataTypeEnum;
import com.rfsp.mcp.feign.NHCJssqFeign;
import com.rfsp.mcp.pojo.dto.*;
import com.rfsp.common.pojo.po.OrgPO;
import com.rfsp.mcp.pojo.po.OrgYbjItfDataPO;
import com.rfsp.mcp.pojo.po.OrgYbjPO;
import com.rfsp.mcp.pojo.po.PfmPO;
import com.rfsp.common.pojo.po.UserPO;
import com.rfsp.mcp.pojo.sdto.*;
import com.rfsp.mcp.pojo.vo.*;
import com.rfsp.mcp.service.*;

import com.rfsp.mcp.service.interfaceclient.WSMiAccountService;
import com.rfsp.mcp.service.interfaceclient.WSMiPayService;
import com.rfsp.mcp.service.interfaceclient.WSOrgSubjectInfoService;
import com.rfsp.mcp.util.McpPdfUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.server.ResponseStatusException;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.*;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.*;
import java.util.List;
import java.util.stream.Collectors;

@RequiresRoles(value={"mcp_bank"}, logical= Logical.AND)
@Controller("BankPayLogController")
@RequestMapping("/bank/payLog")
public class BankPayLogController extends BankController {

    public Logger logger = LoggerFactory.getLogger(BankPayLogController.class);

    @Value("${mcp.file-temp-path-mainInfo}")
    private String mainInfoPath;
    @Value("${mcp.file-temp-path-pay}")
    private String payExcelPath;

    private static final String LDJG_COUNT_LIMIT_PROMPT = "今日次数已用尽，请明日再查！";

    private static List<DictVO> dataTypeList;

    @Autowired
    ParamService paramService;
    
    @Autowired
    PayLogService payLogService;

    @Autowired
    HospitalService hospitalService;

    @Autowired
    AuthService authService;

    @Autowired
    FinanceService financeService;

    @Autowired
    NhcJssqService nhcService;

    @Autowired
    PayService payService;

    @Autowired
    NHCJssqFeign feign;

    @Autowired
    OrgYbjService ybjSerivce;

    @Autowired
    private PfmService pfmService;
    @Autowired
    private OrgYbjService orgYbjService;
    @Autowired
    private OrgService orgService;
    @Autowired
    private WSOrgSubjectInfoService wsOrgSubjectInfoService;
    @Autowired
    private WSMiPayService wsMiPayService;
    @Autowired
    private WSMiAccountService wsMiAccountService;
    @Autowired
    private AccountService accountService;

    @PostConstruct
    public void init() {
        dataTypeList = new ArrayList<>();
        DictVO dictVO1 = new DictVO();
        dictVO1.setCode("1");
        dictVO1.setText("主体信息汇总表");
        dataTypeList.add(dictVO1);
        DictVO dictVO2 = new DictVO();
        dictVO2.setCode("2");
        dictVO2.setText("医保结算账户");
        dataTypeList.add(dictVO2);
        DictVO dictVO3 = new DictVO();
        dictVO3.setCode("3");
        dictVO3.setText("医保结算明细数据");
        dataTypeList.add(dictVO3);
    }

    @RequestMapping("/")
    public String index1(ModelMap model, PageSDTO pageSdto, MiPayLogSDTO sdto) {
        return index(model,pageSdto,sdto);
    }
    @RequestMapping("/index")
    public String index(ModelMap model, PageSDTO pageSdto, MiPayLogSDTO sdto) {
        logger.info(TrcMsg.getMsg(TrcMsg.METHOD_BEGIN, "BankPayLogController.index"));

        sdto=XssUtils.replaceXss(sdto);

        UserPO currentUser = ShiroUtils.getCurrentUser();
        sdto.setQueryOrgId(currentUser.getOrgId());
        sdto.setQueryPayState("1"); //只展示成功数据，所以加此逻辑
        PageInfo<MiPayLogVO> pageInfo = payLogService.get(sdto,pageSdto);
        payLogService.combo(pageInfo.getList());
        sdto=XssUtils.replaceUnXss(sdto);
        ResultListVO<MiPayLogVO> vo = ResultListVO.success(pageInfo,sdto);
        model.put("vo", vo);

        logger.info(TrcMsg.getMsg(TrcMsg.METHOD_END, "BankPayLogController.index"));
        return "bank/payLog/index";
    }
    /*
    @GetMapping("/detail")
    public String detail(ModelMap model,Long id) {
        ResultVO<MiPayLogVO> vo = ResultVO.success(new MiPayLogVO());
        model.put("vo", vo);

        return "bank/payLog1/detail";
    }
    */

    @Token
    @GetMapping("/create")
    public String createForm(ModelMap model,@ModelAttribute("dto") MiPayLogDTO dto,BindingResult bindingResult) {
        logger.info(TrcMsg.getMsg(TrcMsg.METHOD_BEGIN, "BankPayLogController.createForm"));

        dto=XssUtils.replaceXss(dto);
        
        if(dto.getFinanceId()!=null){
            FinanceVO finance=financeService.getById(dto.getFinanceId());
            if(finance.getAuthId()!=null) {
                AuthVO auth=authService.getById(finance.getAuthId());
                //if("1".equals(auth.getAuthStatus())) {
                dto.setAuthId(auth.getId());
                dto.setAuthNo(auth.getAuthNo());
                //}
            }
            if(finance.getOrgId()!=null) {
                HospitalVO hospital = hospitalService.getById(finance.getOrgId());
                dto.setTargetOrgId(hospital.getId());
                dto.setTargetOrgCode(hospital.getOrgCode());
                dto.setTargetOrgName(hospital.getOrgName());
            }
            if(finance.getPfmId() != null) {
            	PfmPO pfmPO = pfmService.get(finance.getPfmId());
            	dto.setMcp_pfm(pfmPO.getItfType());
            	dto.setItfType(pfmPO.getItfType());
            }
        }
        dto=XssUtils.replaceUnXss(dto);
        model.put("dto",dto);
        ResultVO<MiPayLogDTO> result = ResultVO.success(dto);
        model.put("result",result);
        if(bindingResult.hasErrors()) {
            result.setMsg("操作失败");
        }

        logger.info(TrcMsg.getMsg(TrcMsg.METHOD_END, "BankPayLogController.createForm"));
        return "bank/payLog/createForm";
    }

    @Value("${mcp.file-path-paylog}")
    private String filePath;

    @Token(TokenType.refresh)
    @PostMapping("/create")
    public String create(ModelMap model,@ModelAttribute("dto") @Valid MiPayLogDTO dto,BindingResult result) {
        logger.info(TrcMsg.getMsg(TrcMsg.METHOD_BEGIN, "BankPayLogController.create"));
        // 检查验证错误
        if (result.hasErrors()) {
            // 可添加额外处理
            logger.info(TrcMsg.getMsg(TrcMsg.METHOD_END, "BankPayLogController.create"));
            List<ObjectError> allErrors = result.getAllErrors();
            StringBuffer errorMsg = new StringBuffer();
            for (ObjectError allError : allErrors) {
                errorMsg.append(allError.getDefaultMessage());
            }
            return createForm(model,dto,result);
        }
        dto=XssUtils.replaceXss(dto);
        if (dto.getTargetOrgId() == null) {
            logger.info(TrcMsg.getMsg(TrcMsg.METHOD_END, "BankPayLogController.create"));
            result.addError(new FieldError("dto", "global", "请选择医保定点机构名称"));
            return createForm(model,dto,result);
        }
        if (dto.getAuthId() == null) {
            logger.info(TrcMsg.getMsg(TrcMsg.METHOD_END, "BankPayLogController.create"));
            result.addError(new FieldError("dto", "global", "请选择授权书"));
            return createForm(model,dto,result);
        }
        if (dto.getDataType().contains(MiPayDataTypeEnum.MI_PAY.getKey())) {
            if (StringUtils.isBlank(dto.getPayStartDate()) && StringUtils.isNotBlank(dto.getPayEndDate())) {
                logger.info(TrcMsg.getMsg(TrcMsg.METHOD_END, "BankPayLogController.create"));
                result.addError(new FieldError("dto", "global", "请勾选结算起始日期"));
                return createForm(model,dto,result);
            }
            if (StringUtils.isNotBlank(dto.getPayStartDate()) && StringUtils.isBlank(dto.getPayEndDate())) {
                logger.info(TrcMsg.getMsg(TrcMsg.METHOD_END, "BankPayLogController.create"));
                result.addError(new FieldError("dto", "global", "请勾选结算结束日期"));
                return createForm(model,dto,result);
            }
            if (StringUtils.isNotBlank(dto.getPayStartDate()) && StringUtils.isNotBlank(dto.getPayEndDate())) {
                LocalDate payStartDate = DateUtil.parseLocalDateByYYYYMMDD(dto.getPayStartDate());
                LocalDate payEndDate = DateUtil.parseLocalDateByYYYYMMDD(dto.getPayEndDate());
                if (payStartDate.isAfter(payEndDate)) {
                    logger.info(TrcMsg.getMsg(TrcMsg.METHOD_END, "BankPayLogController.create"));
                    result.addError(new FieldError("dto", "global", "开始日期不能晚于结束日期"));
                    return createForm(model,dto,result);
                }
                LocalDate localDate = payStartDate.plusYears(1).minusDays(1);
                if (localDate.isBefore(payEndDate)) {
                    logger.info(TrcMsg.getMsg(TrcMsg.METHOD_END, "BankPayLogController.create"));
                    result.addError(new FieldError("dto", "global", "输入时间请小于1年！"));
                    return createForm(model,dto,result);
                }
                //前年一月一号日期
                LocalDate localDate1 = LocalDate.now().minusYears(2).withMonth(1).withDayOfMonth(1);
                if (payEndDate.isBefore(localDate1)) {
                    logger.info(TrcMsg.getMsg(TrcMsg.METHOD_END, "BankPayLogController.create"));
                    result.addError(new FieldError("dto", "global", "平台支持查询前年1月1日至今的结算数据"));
                    return createForm(model,dto,result);
                }
            }
            if (StringUtils.isBlank(dto.getPayStartDate()) && StringUtils.isBlank(dto.getPayEndDate())) {
                //如用户未填写起止时间，默认为截止日期当期日期，例2025-08-22，起始日期为2024-08-23
                dto.setPayStartDate(DateUtil.parseStrByYYYYMMDD(LocalDate.now().minusYears(1).plusDays(1)));
                dto.setPayEndDate(DateUtil.parseDateToStrByYYYYMMDD(new Date()));
            }
        }else {
            dto.setPayStartDate("");
            dto.setPayEndDate("");
        }

        if ("6".equals(dto.getQueryReasonType())) {
            if (StringUtils.isBlank(dto.getQueryReason()) || dto.getQueryReason().length() > 100) {
                logger.info(TrcMsg.getMsg(TrcMsg.METHOD_END, "BankPayLogController.create"));
                result.addError(new FieldError("dto", "global", "具体内容需要填写，且长度不超过100位"));
                return createForm(model,dto,result);
            }
        }

        UserPO currentUser = ShiroUtils.getCurrentUser();
        dto.setQueryOrgId(currentUser.getOrgId());
        dto.setQueryUsrId(currentUser.getId());
        dto.setOptUserId(currentUser.getId());
        dto.setOptType("1");
//        dto.setTargetOrgId();

//        MiPayLogSDTO sdto=new MiPayLogSDTO();
//        sdto.setQueryOrgId(currentUser.getOrgId());
//        sdto.setTargetOrgId(dto.getTargetOrgId());
//        sdto.setQueryTimeStart(DateUtil.parseStrByYYYYMMDD(LocalDate.now())+" 00:00:00");
//        sdto.setQueryPayState("1");

        //授权有效性验证
        AuthVO auth=authService.getAuthDetailById(dto.getAuthId());
        if(!"1".equals(auth.getAuthStatus())){
            result.addError(new FieldError("dto", "authNo", "无效的授权书，请重新更换！"));
            return createForm(model,dto,result);
        }
        //如果是宿迁用户登录就不显示结算起止时间
        if ("0".equals(auth.getItfType().trim())) {
            dto.setPayStartDate("");
            dto.setPayEndDate("");
        }


//        FinancePO finance=financeService.getByAuthId(auth.getId());
        dto.setPfmId(auth.getPfmId());
        dto.setOrgYbjId(auth.getOrgYbjId());

        //查询医保关联信息
        OrgYbjPO ybj = ybjSerivce.get(auth.getOrgYbjId());
        if(ybj==null){
            result.addError(new FieldError("dto", "global", "查询失败,未找到医保关联信息"));
            return createForm(model,dto,result);
        }
        if(ybj.getOrgNo()==null || "".equals(ybj.getOrgNo())){
            result.addError(new FieldError("dto", "global", "查询失败,未找到医保关联信息"));
            return createForm(model,dto,result);
        }

        Map<String, Boolean> map = null;
        if (StringUtils.isNotBlank(auth.getItfType()) && "1".equals(auth.getItfType().trim())) {
            map = new HashMap<>();
            Integer mcpBankQueryNum = Integer.parseInt(paramService.getValue("MCP_BANK_QUERY_NUM"));//接口调用次数
            //次数限制判断:无论选几个都超次数提示，如果选两个及以上，有一个不超不提示
            boolean mainTime = false;
            if (dto.getDataType().contains(MiPayDataTypeEnum.MI_MAIN.getKey())) {
                Integer ybzhcount = payLogService.getZTSearchSuccessCount(DateUtil.parseStrByYYYYMMDD(LocalDate.now()), DateUtil.parseStrByYYYYMMDD(LocalDate.now().plusDays(1)), dto.getQueryOrgId(), dto.getTargetOrgId(), ybj.getId()); //医保账户信息
                if (ybzhcount >= mcpBankQueryNum) {
                    mainTime = true;
                }
            }
            map.put(MiPayDataTypeEnum.MI_MAIN.getKey(), mainTime);
            boolean accountTime = false;
            if (dto.getDataType().contains(MiPayDataTypeEnum.MI_ACCOUNT.getKey())) {
                Integer ybzhcount = payLogService.getYBZHSearchSuccessCount(DateUtil.parseStrByYYYYMMDD(LocalDate.now()), DateUtil.parseStrByYYYYMMDD(LocalDate.now().plusDays(1)), dto.getQueryOrgId(), dto.getTargetOrgId(), ybj.getId()); //医保账户信息
                if (ybzhcount >= mcpBankQueryNum) {
                    accountTime = true;
                }
            }
            map.put(MiPayDataTypeEnum.MI_ACCOUNT.getKey(), accountTime);
            boolean payTime = false;
            if (dto.getDataType().contains(MiPayDataTypeEnum.MI_PAY.getKey())) {
                Integer jsmxcount = payLogService.getJSMXSearchSuccessCount(DateUtil.parseStrByYYYYMMDD(LocalDate.now()), DateUtil.parseStrByYYYYMMDD(LocalDate.now().plusDays(1)), dto.getQueryOrgId(), dto.getTargetOrgId(), ybj.getId()); //结算明细
                if (jsmxcount >= mcpBankQueryNum) {
                    payTime = true;
                }
            }
            map.put(MiPayDataTypeEnum.MI_PAY.getKey(), payTime);
            String dataType = dto.getDataType();
            String[] split = dataType.split("\\,");
            //次数限制判断:无论选几个都超次数提示，如果选两个及以上，有一个不超不提示
            if (split.length == 1) {
                if (map.get(MiPayDataTypeEnum.MI_MAIN.getKey()) ||
                        map.get(MiPayDataTypeEnum.MI_ACCOUNT.getKey()) ||
                        map.get(MiPayDataTypeEnum.MI_PAY.getKey())) {
                    logger.info(TrcMsg.getMsg(TrcMsg.METHOD_END, "BankPayLogController.create"));
                    result.addError(new FieldError("dto", "global", LDJG_COUNT_LIMIT_PROMPT));
                    return createForm(model,dto,result);
                }
            }
            if (split.length == 3) {
                if (map.get(MiPayDataTypeEnum.MI_MAIN.getKey()) &&
                        map.get(MiPayDataTypeEnum.MI_ACCOUNT.getKey()) &&
                        map.get(MiPayDataTypeEnum.MI_PAY.getKey())) {
                    logger.info(TrcMsg.getMsg(TrcMsg.METHOD_END, "BankPayLogController.create"));
                    result.addError(new FieldError("dto", "global", LDJG_COUNT_LIMIT_PROMPT));
                    return createForm(model,dto,result);
                }
            }
            if (split.length == 2) {
                if ((map.get(MiPayDataTypeEnum.MI_MAIN.getKey()) && map.get(MiPayDataTypeEnum.MI_ACCOUNT.getKey())) ||
                        (map.get(MiPayDataTypeEnum.MI_MAIN.getKey()) && map.get(MiPayDataTypeEnum.MI_PAY.getKey())) ||
                        (map.get(MiPayDataTypeEnum.MI_ACCOUNT.getKey()) && map.get(MiPayDataTypeEnum.MI_PAY.getKey()))) {
                    logger.info(TrcMsg.getMsg(TrcMsg.METHOD_END, "BankPayLogController.create"));
                    result.addError(new FieldError("dto", "global", LDJG_COUNT_LIMIT_PROMPT));
                    return createForm(model,dto,result);
                }
            }
        }else {
            MiPayLogSDTO sdto=new MiPayLogSDTO();
            sdto.setQueryOrgId(currentUser.getOrgId());
            sdto.setTargetOrgId(dto.getTargetOrgId());

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String date=sdf.format(new Date());
            //sdto.setQueryTimeEnd(date);
            //Calendar c = Calendar.getInstance();
            //c.add(Calendar.DATE, -1);
            //date=sdf.format(c.getTime());
            sdto.setQueryTimeStart(date+" 00:00:00");
            sdto.setQueryPayState("1");
            sdto.setPfmId(auth.getPfmId());
            List<MiPayLogVO> voList=payLogService.get(sdto);
            if(voList.size()>=3){
                result.addError(new FieldError("dto", "global", "今日查询次数已用尽，请明日再次提交！"));
                return createForm(model,dto,result);
            }
        }

        if(result.hasErrors()) {
            return createForm(model,dto,result);
        }
        dto.setQueryPayState("0");
        if (StringUtils.isNotBlank(auth.getItfType())){
            dto.setItfType(auth.getItfType().trim());
        }
        Integer count = payLogService.saveMiPayLog(dto, map);
        if(count==0){
            result.addError(new FieldError("dto", "global", "创建查询失败！如有疑问请致电平台客服电话400-009-0001。"));
            return createForm(model,dto,result);
        }
        Long id=dto.getId();
        //需要判断是哪个平台的
        String dataType1 = "1";
        String dataType2 = "1";
        String dataType3 = "1";
        if (StringUtils.isNotBlank(auth.getItfType()) && "1".equals(auth.getItfType().trim())) {
            //下面是调用抚顺的接口
            boolean mainType = false;
            boolean accountType = false;
            boolean payType = false;
            //主体信息汇总表
            if (dto.getDataType().contains(MiPayDataTypeEnum.MI_MAIN.getKey()) && !map.get(MiPayDataTypeEnum.MI_MAIN.getKey())) {
                OrgSubjectInfoDto orgSubjectInfoDto = new OrgSubjectInfoDto();
                orgSubjectInfoDto.setLogId(id);
                orgSubjectInfoDto.setPfmId(dto.getPfmId());
                orgSubjectInfoDto.setMiOrgId(dto.getTargetOrgId());
                orgSubjectInfoDto.setMiOrgCode(ybj.getOrgNo());
                orgSubjectInfoDto.setOptUserId(currentUser.getId());
                ResultVO<String> stringResultVO = wsOrgSubjectInfoService.queryOrgSubjectInfo(orgSubjectInfoDto);
                if ("200".equals(stringResultVO.getCode())) {
                    mainType = true;
                }else {
                    dataType1 = "0";
                }
            }
            //医保结算账户
            if (dto.getDataType().contains(MiPayDataTypeEnum.MI_ACCOUNT.getKey()) && !map.get(MiPayDataTypeEnum.MI_ACCOUNT.getKey())) {
                MiAccountInfoDto miAccountInfoDto =new MiAccountInfoDto();
                miAccountInfoDto.setLogId(id);
                miAccountInfoDto.setPfmId(dto.getPfmId());
                miAccountInfoDto.setMiOrgId(dto.getTargetOrgId());
                miAccountInfoDto.setMiOrgCode(ybj.getOrgNo());
                ResultVO<String> stringResultVO = wsMiAccountService.queryMiAccountInfo(miAccountInfoDto);
                if ("200".equals(stringResultVO.getCode())) {
                    accountType = true;
                }else {
                    dataType2 = "0";
                }
            }
            //医保结算明细数据
            if (dto.getDataType().contains(MiPayDataTypeEnum.MI_PAY.getKey()) && !map.get(MiPayDataTypeEnum.MI_PAY.getKey())) {
                MiPayInfoDto miPayInfoDto=new MiPayInfoDto();
                miPayInfoDto.setPfmId(dto.getPfmId());
                miPayInfoDto.setLogId(id);
                miPayInfoDto.setMiOrgId(dto.getTargetOrgId());
                miPayInfoDto.setMiOrgCode(ybj.getOrgNo());
                miPayInfoDto.setPayStartDate(dto.getPayStartDate());
                miPayInfoDto.setPayEndDate(dto.getPayEndDate());
                miPayInfoDto.setOptUserId(currentUser.getId());
                ResultVO<String> stringResultVO = wsMiPayService.queryMiPayInfo(miPayInfoDto);
                if ("200".equals(stringResultVO.getCode())) {
                    payType = true;
                }else {
                    dataType3 = "0";
                }
            }

            if (mainType || accountType || payType) {
                MiPayLogDTO updateDto = new MiPayLogDTO();
                updateDto.setQueryPayState("1");
                if ("0".equals(dataType1)) {
                    updateDto.setDataType1(dataType1);
                }
                if ("0".equals(dataType2)) {
                    updateDto.setDataType2(dataType2);
                }
                if ("0".equals(dataType3)) {
                    updateDto.setDataType3(dataType3);
                }
                payLogService.updateById(id, updateDto);
            }else {
                result.addError(new FieldError("dto", "global", "创建查询失败！如有疑问请致电平台客服电话400-009-0001。"));
                return createForm(model,dto,result);
            }
        }else {
            //下面是调用宿迁的接口
            Integer payCount=0;
            String fileName=id+".txt";
            String filePath = this.filePath.replaceFirst("date/", StringUtil.dateToString(new Date(), "yyyy/MM/dd/"));
            HospitalVO hospital=hospitalService.getById(dto.getTargetOrgId());
            try{
                NhcJssqSDTO sdto1=new NhcJssqSDTO();
                sdto1.setIdNo(ybj.getOrgNo());
                ResultVO<List<NhcJssqVO>> result1=nhcService.query(sdto1,hospital.getOrgCode(),filePath,fileName);
                if(!"000000".equals(result1.getCode())){
                    result.addError(new FieldError("dto", "global", "医保结算信息查询失败，请稍后查询！如有疑问请致电平台客服电话400-009-0001。"));
                    return createForm(model,dto,result);
                }
                ResultVO<List<NhcJssqVO>> result2=nhcService.filter(result1,sdto1.getIdNo());
                List<MiPayDTO> payList=nhcService.getList(result2.getData());
                payCount=payService.createByPayLog(dto,payList);
                if(payCount>0) {
                    MiPayLogDTO updateDto = new MiPayLogDTO();
                    updateDto.setQueryPayState("1");
                    updateDto.setFilePath(filePath + fileName);
                    payLogService.updateById(id, updateDto);
                }
            }catch (Exception ex){
                log.error(ex.getMessage());
            }
            if(payCount==0){
                result.addError(new FieldError("dto", "global", "未查询到相关的医保结算信息，请稍后查询！如有疑问请致电平台客服电话400-009-0001。"));
                return createForm(model,dto,result);
            }
        }

        logger.info(TrcMsg.getMsg(TrcMsg.METHOD_END, "BankPayLogController.create"));

        //融资申请跳转到详情页面
//        if("finance".equals(dto.getFrom())){
//            return this.alertLocation(model,"操作成功","/mcp/base/payLog/detail?id="+dto.getId()+"&aid="+dto.getAid());
//        }
        return this.alertParentReload(model,"操作成功");
        //return this.alertLocation(model,"操作成功","./");
    }









    @RequestMapping("/hospitalSelector")
    public String productSelector(ModelMap model, PageSDTO pageSDTO,HospitalSDTO sdto) {
        logger.info(TrcMsg.getMsg(TrcMsg.METHOD_BEGIN, "BankPayLogController.hospitalSelector"));

        sdto=XssUtils.replaceXss(sdto);
        UserPO currentUser = ShiroUtils.getCurrentUser();
//        PageInfo<HospitalVO> page = hospitalService.get(sdto,pageSDTO);
        sdto.setOrgId(currentUser.getOrgId());
        PageInfo<HospitalVO> page = hospitalService.findByWhere(sdto, pageSDTO);
        hospitalService.combo(page.getList());
        sdto=XssUtils.replaceUnXss(sdto);
        ResultListVO<HospitalVO> vo = ResultListVO.success(page,sdto);
        model.put("vo", vo);

        logger.info(TrcMsg.getMsg(TrcMsg.METHOD_END, "BankPayLogController.hospitalSelector"));
        return "bank/payLog/hospitalSelector";
    }

    @RequestMapping("/hospitalDetail")
    @ResponseBody
    public ResultVO hospitalDetail(ModelMap model,Long id) {
        logger.info(TrcMsg.getMsg(TrcMsg.METHOD_BEGIN, "BankPayLogController.hospitalDetail"));

        HospitalVO vo=hospitalService.getById(id);
        vo.setOrgName(AppUtil.fStr(vo.getOrgName()));

        hospitalService.combo(vo);
        ResultVO<HospitalVO> r = ResultVO.success(vo);
        model.put("vo", r);

        logger.info(TrcMsg.getMsg(TrcMsg.METHOD_END, "BankPayLogController.hospitalDetail"));
        return r;
    }


    @RequestMapping("/authSelector")
    public String authSelector(ModelMap model, PageSDTO pageSdto, AuthSDTO sdto) {
        logger.info(TrcMsg.getMsg(TrcMsg.METHOD_BEGIN, "BankPayLogController.authSelector"));

        sdto=XssUtils.replaceXss(sdto);

        UserPO currentUser = ShiroUtils.getCurrentUser();
        sdto.setBankOrgId(currentUser.getOrgId());
        PageInfo<AuthVO> page =authService.get(sdto,pageSdto);
        authService.combo(page.getList());
        sdto=XssUtils.replaceUnXss(sdto);
        ResultListVO<AuthVO> vo = ResultListVO.success(page,sdto);
        model.put("vo", vo);

        logger.info(TrcMsg.getMsg(TrcMsg.METHOD_END, "BankPayLogController.authSelector"));
        return "bank/payLog/authSelector";
    }

    @RequestMapping("/authDetail")
    @ResponseBody
    public ResultVO authDetail(ModelMap model,Long id) {
        logger.info(TrcMsg.getMsg(TrcMsg.METHOD_BEGIN, "BankPayLogController.authDetail"));
        AuthVO vo=authService.getAuthDetailById(id);
        authService.combo(vo);
        ResultVO<AuthVO> r = ResultVO.success(vo);
        model.put("vo", r);
        logger.info(TrcMsg.getMsg(TrcMsg.METHOD_END, "BankPayLogController.authDetail"));
        return r;
    }





    @Value("${mcp.file-temp-path}")
    String tempPath;

    @RequestMapping("/downloadDetail")
    public void downloadDetail(ModelMap model, Long id,String aid,HttpServletRequest request, HttpServletResponse response) throws Exception {
        logger.info(TrcMsg.getMsg(TrcMsg.METHOD_BEGIN, "BankPayLogController.downloadDetail"));
        MiPayLogVO vo=payLogService.getById(id);
        if (!vo.getAid().equals(aid)) {
            throw new ResponseStatusException(HttpStatus.FORBIDDEN, "无访问权限");
        }
        payLogService.combo(vo);
        List<String> payLogCodes = vo.getPayLogCodes();
        //0代表不能下载
        if ("0".equals(vo.getDownloadEnabled()) || payLogCodes.size() == 0) {
            throw new ResponseStatusException(HttpStatus.FORBIDDEN, "无访问权限");
        }

        String itfType = "0";
        String dataSource = "";
        PfmVO pfmVO = pfmService.findByPayLogId(id);
        if (pfmVO != null) {
            if (StringUtils.isNotBlank(pfmVO.getItfType())) {
                itfType = pfmVO.getItfType().trim();
            }
            dataSource = pfmVO.getPfmName();
        }
        if ("0".equals(itfType)) {
            downloadDetailPl(model, vo, id, request, response);
        }else {
            try{
                if (payLogCodes.size() == 1 && payLogCodes.get(0).startsWith("GREG")) {
                    //主体信息汇总表下载--PDF-不展示最新的，展示当时查询的
//                    OrgYbjPO orgYbjPO = orgYbjService.findByOrgIdAndPfmId(vo.getTargetOrgId(), vo.getPfmId());
                    OrgYbjItfDataPO orgYbjItfDataPO = wsOrgSubjectInfoService.getOrgYbjItfDataByPayLogId(id);
                    OrgYbjPO orgYbjPO = null;
                    if (orgYbjItfDataPO != null) {
                        orgYbjPO = new OrgYbjPO();
                        BeanUtils.copyProperties(orgYbjItfDataPO,orgYbjPO);
                    }
                    //查询医保关联信息
//                    if(orgYbjPO == null || orgYbjPO.getOrgNo()==null || "".equals(orgYbjPO.getOrgNo())){
//                        throw new ResponseStatusException(HttpStatus.FORBIDDEN, "无访问权限");
//                    }
                    OrgPO orgPO = orgService.findById(vo.getTargetOrgId());
                    HospitalYBDPdfVO hospitalYBDPdfVO = payLogService.coverYBDPdfVO(orgPO, orgYbjPO, vo.getQueryTime(), dataSource);
                    Map<String,Object> dataMap = JsonUtil.toBean(JsonUtil.toJson(hospitalYBDPdfVO), Map.class);
                    dataMap = XssUtils.replaceUnXss(dataMap);
                    String fileName = orgPO.getOrgCode() + ".pdf";
                    boolean deleteFile = true;
                    //生成文件
                    McpPdfUtil.buildMainInfoPDF(dataMap, fileName, mainInfoPath);
                    //通过response返回前端
                    McpPdfUtil.responseMainInfoPDF(response, mainInfoPath, fileName, deleteFile);
                }
                if (payLogCodes.size() == 1 && payLogCodes.get(0).startsWith("GPL")) {
                    //医保结算信息下载--EXCEL
                    //查询医保关联信息
//                    OrgYbjPO ybj = ybjSerivce.get(vo.getOrgYbjId());
//                    if(ybj==null){
//                        throw new ResponseStatusException(HttpStatus.FORBIDDEN, "无访问权限");
//                    }
//                    if(ybj.getOrgNo()==null || "".equals(ybj.getOrgNo())){
//                        throw new ResponseStatusException(HttpStatus.FORBIDDEN, "无访问权限");
//                    }
                    //获取医保账户信息
//                    MiAccountVO accountVO = accountService.findByPfmIdAndOrgNo(vo.getPfmId(), ybj.getOrgNo(), orgId);
                    MiAccountVO accountVO = payLogService.findMiAccountVOByPayLogId(vo.getId());
                    if (accountVO == null) {
                        accountVO = new MiAccountVO();
                    }
//                    MiPaySDTO sdto = new MiPaySDTO();
//                    sdto.setPfmId(vo.getPfmId());
//                    sdto.setOrgNo(ybj.getOrgNo());
//                    sdto.setQueryOrgId(vo.getQueryOrgId());
//                    sdto.setTargetOrgId(vo.getTargetOrgId());
                    //获取结算信息
                    MiPaySDTO sdto = new MiPaySDTO();
                    sdto.setPayLogId(id);
                    sdto.setGplFlag("0");
                    PageInfo<MiPayVO> list = payService.getList(sdto, null);
                    List<MiPayVO> voList = list.getList();
                    String fileName = "医保结算信息表-" + System.currentTimeMillis() + ".xlsx";
                    boolean deleteFile = true;
                    List<MiPayVO> collect = voList.stream().map(miPayVO -> XssUtils.replaceUnXss(miPayVO)).collect(Collectors.toList());
                    payService.buildDetailFile(XssUtils.replaceUnXss(accountVO), collect, fileName, vo.getQueryTime());
                    payService.responseDetailFile(response, fileName, deleteFile);
                }
                if (payLogCodes.size() == 2) {
                    List<Map<String, String>> mapList = new ArrayList<>();

                    //压缩zip
                    //主体信息汇总表下载--PDF-不展示最新的，展示当时查询的
//                    OrgYbjPO orgYbjPO = orgYbjService.findByOrgIdAndPfmId(vo.getTargetOrgId(), vo.getPfmId());
                    OrgYbjItfDataPO orgYbjItfDataPO = wsOrgSubjectInfoService.getOrgYbjItfDataByPayLogId(id);
                    OrgYbjPO orgYbjPO = null;
                    if (orgYbjItfDataPO != null) {
                        orgYbjPO = new OrgYbjPO();
                        BeanUtils.copyProperties(orgYbjItfDataPO,orgYbjPO);
                    }
                    //查询医保关联信息
//                    if(orgYbjPO == null || orgYbjPO.getOrgNo()==null || "".equals(orgYbjPO.getOrgNo())){
//                        throw new ResponseStatusException(HttpStatus.FORBIDDEN, "无访问权限");
//                    }
                    OrgPO orgPO = orgService.findById(vo.getTargetOrgId());
                    HospitalYBDPdfVO hospitalYBDPdfVO = payLogService.coverYBDPdfVO(orgPO, orgYbjPO, vo.getQueryTime(), dataSource);
                    Map<String,Object> dataMap = JsonUtil.toBean(JsonUtil.toJson(hospitalYBDPdfVO), Map.class);
                    dataMap = XssUtils.replaceUnXss(dataMap);
                    String fileName = orgPO.getOrgCode() + ".pdf";
                    McpPdfUtil.buildMainInfoPDF(dataMap, fileName, mainInfoPath);
                    Map<String, String> pdfMap = new HashMap<>();
                    pdfMap.put("filePath", mainInfoPath + fileName);
                    pdfMap .put("fileName", fileName);
                    mapList.add(pdfMap);
                    //医保结算信息下载--EXCEL
                    UserPO currentUser = ShiroUtils.getCurrentUser();
//                    Long orgId = currentUser.getOrgId();

                    //获取医保账户信息
//                    MiAccountVO accountVO = accountService.findByPfmIdAndOrgNo(vo.getPfmId(), orgYbjPO.getOrgNo(), orgId);
                    MiAccountVO accountVO = payLogService.findMiAccountVOByPayLogId(vo.getId());
                    if (accountVO == null) {
                        accountVO = new MiAccountVO();
                    }
                    //获取结算信息
                    MiPaySDTO sdto = new MiPaySDTO();
                    sdto.setPayLogId(id);
                    sdto.setGplFlag("0");
                    PageInfo<MiPayVO> list = payService.getList(sdto, null);
                    List<MiPayVO> voList = list.getList();
                    List<MiPayVO> collect = voList.stream().map(miPayVO -> XssUtils.replaceUnXss(miPayVO)).collect(Collectors.toList());
                    String fileName2 = "医保结算信息表-" + System.currentTimeMillis() + ".xlsx";
                    Map<String, String> mainInfoMap = new HashMap<>();
                    payService.buildDetailFile(XssUtils.replaceUnXss(accountVO), collect, fileName2, vo.getQueryTime());
                    mainInfoMap.put("filePath", payExcelPath + fileName2);
                    mainInfoMap .put("fileName", fileName2);
                    mapList.add(mainInfoMap);

                    String zipFileName = "医保结算信息-" + System.currentTimeMillis() + ".zip";
//                    FileUtil.compress(mapList, payExcelPath + zipFileName, false);
                    FileUtil.compressFiles(mapList, payExcelPath + zipFileName);
                    //删除原始文件
                    for (int i = 0; i < mapList.size(); i++) {
                        String relativePath = mapList.get(i).get("filePath");
                        File file = new File(relativePath);
                        if (file.exists()) {
                            boolean delete = file.delete();
                        }
                    }
                    // 1. 设置响应头 —— attachment 表示下载
                    Path zipPath = Paths.get(payExcelPath + zipFileName);
                    String encoded = URLEncoder.encode(zipFileName, "UTF-8").replace("+", "%20");
                    response.setContentType("application/zip");
                    response.setHeader("Content-Disposition",
                            "attachment; filename=\"" + encoded + "\";" +
                                    "filename*=utf-8''" + encoded);
                    response.setHeader("Content-Length", String.valueOf(Files.size(zipPath)));
                    BufferedInputStream bis = null;
                    OutputStream os = null;
                    try (InputStream fis = Files.newInputStream(zipPath)) {
                        bis = new BufferedInputStream(fis);
                        os = response.getOutputStream();
                        // 3. 使用缓冲区高效传输（8KB缓冲区）
                        byte[] buffer = new byte[8192];
                        int bytesRead;
                        while ((bytesRead = bis.read(buffer)) != -1) {
                            os.write(buffer, 0, bytesRead);
                        }
                        os.flush();
                        Files.deleteIfExists(zipPath);
                    } catch (NoSuchFileException e) {
                        // 4. 处理文件不存在异常
                        response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                        log.error("文件不存在异常,{}", e);
                    } catch (IOException e) {
                        // 处理其他IO异常
                        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                        log.error("IO流异常异常,{}", e);
                    }finally {
                        if (bis != null) {
                            bis.close();
                        }
                    }
                }
            } catch (Exception e) {
                log.error("生成文件异常,{}", e);
            }
        }
        logger.info(TrcMsg.getMsg(TrcMsg.METHOD_END, "BankPayLogController.downloadDetail"));
    }

    private void downloadDetailPl(ModelMap model, MiPayLogVO vo, Long id, HttpServletRequest request, HttpServletResponse response) throws Exception {
        ResultVO<MiPayLogVO> r = ResultVO.success(vo);
        model.put("vo", r);
//        MiPaySDTO sdto=new MiPaySDTO();
//        sdto.setPayLogId(vo.getId());
        MiPaySDTO sdto = new MiPaySDTO();
        sdto.setPayLogId(vo.getId());
        sdto.setGplFlag("1");
        PageInfo<MiPayVO> info = payService.getList(sdto, null);
        List<MiPayVO> payVoList = info.getList();
//        List<MiPayVO> payVoList=payService.get(sdto);

        payService.combo(payVoList);

        for(MiPayVO pay:payVoList){
            pay.setPayMc(AppUtil.fStr(pay.getPayMc()));
        }
        String modelPath = "excelTemplates/bank/payLog/detail.xls";
//        Map<String,Object> resultMap = new HashMap<String,Object>();
//        resultMap.put("resultList", payVoList);
        String fileName = "医保结算信息查询结果.xls";

        payService.buildPlDetailFile(payVoList, modelPath, fileName, response);
//        ExcelUtil.toExcel(resultMap, modelPath, "医保结算信息查询结果.xls",response,request);
    }


    @GetMapping("/showMainInfoForNew")
    public String showMainInfoForNew(ModelMap model, Long payLogId, Long targetOrgId, Long pfmId) throws JsonProcessingException {
        logger.info(TrcMsg.getMsg(TrcMsg.METHOD_BEGIN, "BankPayLogController.showMainInfoForNew"));
        //进入抚顺医保贷
        MiPayLogVO miPayLogVO = payLogService.getById(payLogId);
        OrgYbjPO orgYbjPO = orgYbjService.get(miPayLogVO.getOrgYbjId());
        if(orgYbjPO==null){
            throw new ResponseStatusException(HttpStatus.FORBIDDEN, "无访问权限");
        }
        if(orgYbjPO.getOrgNo()==null || "".equals(orgYbjPO.getOrgNo())){
            throw new ResponseStatusException(HttpStatus.FORBIDDEN, "无访问权限");
        }
        OrgPO orgPO = orgService.findById(targetOrgId);
        String dataSource = "";
        PfmVO pfmVO = pfmService.getById(pfmId);
        if (pfmVO != null) {
            dataSource = pfmVO.getPfmName();
        }

//        MiPayLogVO miPayLogVONew = payLogService.findLastOne(miPayLogVO);
        HospitalYBDPdfVO hospitalYBDPdfVO = payLogService.coverYBDPdfVO(orgPO, orgYbjPO, new Date(), dataSource);
        hospitalYBDPdfVO.setTargetOrgId(targetOrgId);
        hospitalYBDPdfVO.setPfmId(pfmId);
        hospitalYBDPdfVO.setPayLogId(payLogId);
        Map<String,Object> dataMap = JsonUtil.toBean(JsonUtil.toJson(hospitalYBDPdfVO), Map.class);
        dataMap = XssUtils.replaceUnXss(dataMap); //特殊字符会被转义
        model.put("vo", dataMap);
        logger.info(TrcMsg.getMsg(TrcMsg.METHOD_END, "BankPayLogController.showMainInfoForNew"));
        return "bank/payLog/showMainInfoForNew";
    }

    @RequestMapping("/download")
    public void download(HttpServletResponse response, Long payLogId, Long targetOrgId, Long pfmId) throws Exception {
        MiPayLogVO miPayLogVO = payLogService.getById(payLogId);
        OrgYbjPO orgYbjPO = orgYbjService.get(miPayLogVO.getOrgYbjId());
        if(orgYbjPO==null){
            throw new ResponseStatusException(HttpStatus.FORBIDDEN, "无访问权限");
        }
        if(orgYbjPO.getOrgNo()==null || "".equals(orgYbjPO.getOrgNo())){
            throw new ResponseStatusException(HttpStatus.FORBIDDEN, "无访问权限");
        }
        OrgPO orgPO = orgService.findById(targetOrgId);
        String dataSource = "";
        PfmVO pfmVO = pfmService.getById(pfmId);
        if (pfmVO != null) {
            dataSource = pfmVO.getPfmName();
        }
//        MiPayLogVO miPayLogVONew = payLogService.findLastOne(miPayLogVO);
        HospitalYBDPdfVO hospitalYBDPdfVO = payLogService.coverYBDPdfVO(orgPO, orgYbjPO, new Date(), dataSource);
        Map<String,Object> dataMap = JsonUtil.toBean(JsonUtil.toJson(hospitalYBDPdfVO), Map.class);
        dataMap = XssUtils.replaceUnXss(dataMap);
        String fileName = orgPO.getOrgCode() + ".pdf";
        boolean deleteFile = true;
        //生成文件
        McpPdfUtil.buildMainInfoPDF(dataMap, fileName, mainInfoPath);
        //通过response返回前端
        McpPdfUtil.responseMainInfoPDF(response, mainInfoPath, fileName, deleteFile);
    }

    @RequestMapping("/list")
    public String list(MiPaySDTO sdto, ModelMap model, PageSDTO pageSdto,HttpServletRequest request, HttpServletResponse response) throws Exception {
        logger.info(TrcMsg.getMsg(TrcMsg.METHOD_BEGIN, "BankPayLogController.list"));
        String itfType = "0";
        String dataSource = "";
        PfmVO pfmVO = pfmService.findByPayLogId(sdto.getPayLogId());
        if (pfmVO != null) {
            if (StringUtils.isNotBlank(pfmVO.getItfType())) {
                itfType = pfmVO.getItfType().trim();
            }
            dataSource = pfmVO.getPfmName();
        }
        MiPayLogVO miPayLogVO = payLogService.getById(sdto.getPayLogId());
//        sdto.setPayLogCode(miPayLogVO.getPayLogCode());
        if (sdto.getPayLogCode().startsWith("PL")) {
            sdto.setGplFlag("1");
        }else {
            sdto.setGplFlag("0");
        }
        PageInfo<MiPayVO> info = payService.getList(sdto, pageSdto);
        payService.combo(XssUtils.replaceUnXss(info.getList()));
        ResultListVO<MiPayVO> vo = ResultListVO.success(info,sdto);
        model.put("vo", vo);
//        model.put("financeStatusList", McpDictCache.getFinanceStatusDict());
//        model.put("authorizeStatusList", McpDictCache.getAuthorizeStatusDict());
//        model.put("financeViewStatusList", McpDictCache.getFinanceViewStatusDict());
//        model.put("revokeVerifyStatusList", McpDictCache.getRevokeVerifyStatusDict());
        model.put("platList", payLogService.getPlatDict(pfmService));
        model.put("dto", sdto);
        logger.info(TrcMsg.getMsg(TrcMsg.METHOD_END, "BankPayLogController.list"));
        if ("0".equals(itfType)) {
            //跳PL页面
            return "bank/payLog/list.html";
        }else {
            //跳GPL页面
            if (sdto.getPayLogCode().startsWith("GREG")) {
                OrgYbjPO orgYbjPO = null;
                OrgYbjItfDataPO orgYbjItfDataPO = wsOrgSubjectInfoService.getOrgYbjItfDataByPayLogId(sdto.getPayLogId());
                if (orgYbjItfDataPO != null) {
                    orgYbjPO = new OrgYbjPO();
                    BeanUtils.copyProperties(orgYbjItfDataPO,orgYbjPO);
                }
                OrgPO orgPO = orgService.findById(sdto.getTargetOrgId());
                HospitalYBDPdfVO hospitalYBDPdfVO = payLogService.coverYBDPdfVO(orgPO, orgYbjPO, miPayLogVO.getQueryTime(), dataSource);
                Map<String,Object> dataMap = JsonUtil.toBean(JsonUtil.toJson(hospitalYBDPdfVO), Map.class);
                dataMap = XssUtils.replaceUnXss(dataMap);
                model.put("vo", dataMap);
                return "bank/payLog/showMainInfo";
            }else {
                //获取账户信息
                MiAccountVO miAccountVO = payLogService.findMiAccountVOByPayLogId(sdto.getPayLogId());
                if (miAccountVO == null) {
                    miAccountVO = new MiAccountVO();
                }
                miAccountVO = XssUtils.replaceUnXss(miAccountVO);
                model.put("miAccountVO", miAccountVO);
                return "bank/payLog/gplList.html";
            }
        }
    }
}
